package com.sharp.oss.service.impl;

import com.sharp.kernel.constant.err.ErrCodeSys;
import com.sharp.kernel.exception.ServiceException;
import com.sharp.framework.service.cache.FrameCacheService;
import com.sharp.kernel.utils.DateUtil;
import com.sharp.framework.utils.HttpUtil;
import com.sharp.kernel.validate.Validator;
import com.sharp.oss.constant.ObjectStorageConst;
import com.sharp.oss.constant.param.ObjectStorageParamConst;
import com.sharp.oss.dao.entity.SaObjectStorage;
import com.sharp.oss.dao.repository.SaObjectStorageService;
import com.sharp.oss.service.ObjectStorageService;
import com.sharp.oss.vo.UploadVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;

/**
 * Title: ObjectStorageServiceLocalImpl
 * Description: Copyright: Copyright (c) 2019 Company: BHFAE
 *
 * @author Sharp
 * @date 2019/10/16 21:10
 * @description Project Name:
 * @Package: com.srct.service.service.impl
 */
@Slf4j
@Service
public class ObjectStorageServiceLocalImpl implements ObjectStorageService {

    private static final String TYPE = "LOCAL";

    @Resource
    private FrameCacheService frameCacheService;
    @Resource
    private SaObjectStorageService saObjectStorageService;
    @Value("${my.project.name}")
    private String projectName;

    @Override
    public UploadVO upload(HttpServletRequest request, MultipartFile file, String fileName, String type) {
        String name = file.getOriginalFilename();
        long fileSize = 0L;
        if (StringUtils.isBlank(fileName)) {
            fileName = buildFileName(name, HttpUtil.getRemoteIp(request));
        }

        String folderName = frameCacheService.getParamValueAvail(ObjectStorageParamConst.OSS_UPLOAD_PATH) + ObjectStorageConst.SEP + projectName;
        if (StringUtils.isNotBlank(type)) {
            folderName = folderName + ObjectStorageConst.SEP + type;
        } else {
            type = TYPE;
        }
        folderName = folderName + ObjectStorageConst.SEP + DateUtil.formatDate(new Date(), DateUtil.DATE);
        try {
            InputStream inputStream = file.getInputStream();
            Path directory = Paths.get(folderName);
            if (!Files.exists(directory)) {
                Files.createDirectories(directory);
            }
            log.info("folderName: {}, fileName: {}", folderName, fileName);
            fileSize = Files.copy(inputStream, directory.resolve(fileName), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new ServiceException("上传文件失败", e);
        }
        String url = buildAccessUrl(folderName, fileName);
        record(fileName, type, url, file.getSize());
        return buildUploadVO(fileName, fileSize, url);
    }

    @Override
    public void delete(Long id) {
        SaObjectStorage os = saObjectStorageService.selectByPrimaryKey(id);
        String domain = frameCacheService.getParamValueAvail(ObjectStorageParamConst.OSS_ACCESS_DOMAIN);
        String url = os.getUri();
        String fileName = url.substring(domain.length());
        File file = new File(fileName);
        Validator.assertTrue(file.exists(), ErrCodeSys.PA_DATA_NOT_EXIST, "删除文件");
        Validator.assertTrue(file.delete(), ErrCodeSys.SYS_ERR_MSG, "删除文件失败");
        file.delete();
        saObjectStorageService.deleteByPrimaryKey(id);
    }
}
